package com.glela.controller;

import com.alibaba.fastjson.JSONObject;
import com.glela.api.im.util.IMConfig;
import com.glela.cache.model.RedisKey;
import com.glela.cache.redis.RedisKeys;
import com.glela.common.constant.CommonConstants;
import com.glela.common.util.JsonUtil;
import com.glela.common.util.LinkUtil;
import com.glela.goods.model.LiveShareRecord;
import com.glela.goods.service.LiveShareRecordService;
import com.glela.live.messages.ChatRoomDateMessage;
import com.glela.live.messages.RedPackageMessage;
import com.glela.live.model.LivePlan;
import com.glela.live.model.LiveShareClickRecord;
import com.glela.live.model.ShareRankingListVo;
import com.glela.live.models.ChatRoomInfo;
import com.glela.live.models.CodeSuccessResult;
import com.glela.live.service.ChatRoomService;
import com.glela.live.service.LivePlanService;
import com.glela.live.service.LiveShareClickRecordService;
import com.glela.live.util.LiveConfig;
import com.glela.live.util.RandomCharUtil;
import com.glela.live.util.RongCloud;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.util.ParameterUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.swing.text.html.parser.Entity;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jinweiwei on 2018/3/2.
 */
@RestController
@RequestMapping("/livePlan")
public class LivePlanController extends LiveBaseController {

	private static Logger logger = LoggerFactory.getLogger(LivePlanController.class);

	@Autowired
	private LivePlanService livePlanService;

	@Autowired
    private ChatRoomService chatRoomService;

	@Autowired
    private BaseRestrictionsService baseRestrictionsService;

	@Autowired
	private LiveShareClickRecordService liveShareClickRecordService;

	@Autowired
	private LiveShareRecordService liveShareRecordService;

	/**
	 * 
	* **********************************************
	* @Title: live 
	* @Description: 直播计划列表获取接口
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author wy	
	* @date 2018年03月06日 下午4:13:11 
	* **********************************************
	 */
	@RequestMapping(value = "/getActiveList", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getLivePlanList(HttpServletRequest request) {
		try {
            if (ParameterUtils.validParams(request.getHeader("userId"))){
                return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
            }
            BaseRestrictions restrictions = baseRestrictionsService.getBaseRestrictionsForCache("validtionLiveUser");
            if (null != restrictions && restrictions.getStatus()==1) {
                if (StringUtils.isNotBlank(restrictions.getName())){
                    if (!Arrays.asList(restrictions.getName().split(",")).contains(request.getHeader("userId"))){
                        HashMap<Object, Object> map = new HashMap<>();
                        map.put("active", null);
                        map.put("isValue", 0); //0 false
                        return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
                    }
                }
            }
			HashMap<Object, Object> map = new HashMap<>();
			String redisContent = redisUtil.get(RedisKey.REDIS_KEY_LIVEROOM_PLAN_MODEL);
			if (StringUtils.isNotBlank(redisContent)) {
                LivePlan livePlan = JsonUtil.toBean(redisContent, LivePlan.class);
                livePlan.setAddUserNum(0);
                map.put("active",livePlan);
				map.put("isValue", 1); //1  true)
				return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
			}
			LivePlan livePlan = livePlanService.getLivePlan();
			if(null == livePlan ){
				map.put("active", livePlan);
				map.put("isValue", 0); //0 false
				return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
			}
				livePlan.setAddUserNum(0);
				map.put("active", livePlan);
				map.put("isValue", 1); //1  true
				redisUtil.set(RedisKey.REDIS_KEY_LIVEROOM_PLAN_MODEL, livePlan);
				return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("获取直播计划列表异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	@RequestMapping(value = "/startLiving", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> startLiving(@RequestBody JSONObject json){
	    if (StringUtils.isBlank(json.getString("id"))){
            return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C20102), HttpStatus.OK);
        }
        LivePlan livePlan = livePlanService.getById(Integer.valueOf(json.getString("id")));
        if (livePlan==null){
            return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C90001), HttpStatus.OK);
        }
        /*if (livePlan.getStatus()==2){
        	logger.error("=================直播中刷新首页直播对象/直播计划对象缓存============="+json.toJSONString());
			redisUtil.del(RedisKey.REDIS_KEY_LIVEROOM_PLAN_MODEL);
			redisUtil.del(RedisKey.REDIS_KEY_LIVE_PLAN_DETAIL+json.getString("id"));
//			redisUtil.del(RedisKeys.LIVE_SALE_GOODS+json.getString("id"));
			//设置当前直播间正在执行的是哪个直播计划
			redisUtil.set(RedisKeys.LIVE_ROOM_EXECUT_LIVE_PLAN+json.getString("id"),1);
            return new ResponseEntity<>(new ResponseResultModel<>(null), HttpStatus.OK);
        }*/
        if (livePlan.getStatus()==3){
            return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C90003), HttpStatus.OK);
        }
        logger.error("======startLiving========直播计划变更为开始状态==========="+json.toJSONString());
	    int planId = json.getInteger("id");
	    final int pid = planId;
		redisUtil.del(RedisKey.REDIS_KEY_LIVEROOM_PLAN_MODEL);
        redisUtil.del(RedisKey.REDIS_KEY_LIVE_PLAN_DETAIL+planId);
		redisUtil.del(RedisKeys.LIVE_SALE_GOODS+planId);
		//设置当前直播间正在执行的是哪个直播计划
		redisUtil.set(RedisKeys.LIVE_ROOM_EXECUT_LIVE_PLAN+planId,1);
        ChatRoomInfo[] chatroomCreateChatRoomInfo = {new ChatRoomInfo(planId+"","" )};
        try {
            RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).chatroom.create(chatroomCreateChatRoomInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
		/*//设置直播计划的点赞总数缓存
		redisUtil.set(RedisKeys.LIVE_PLAN_TOTAL_LIKE_NUM+planId,0);*/
		//定时记录实时在线人数
        Thread t = new Thread(new Runnable(){
            public void run(){
                while (StringUtils.isNotBlank(redisUtil.get(RedisKeys.LIVE_ROOM_EXECUT_LIVE_PLAN+pid))){
                    try {
                    	logger.error("===============addLiveAudience====pid："+pid+"=========当前时间："+System.currentTimeMillis());
						chatRoomService.addLiveAudience(Integer.valueOf(pid));
						//如需循环下发总人数/总赞数在此调用下发消息接口即可
//						chatRoomService.mngSendMessage()
                        Thread.sleep(CommonConstants.sendChatRoomInfoRate);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }});
        t.start();
		//删除计划列表重新缓存 缓存商品列表
		return new ResponseEntity<>(new ResponseResultModel<>(null), HttpStatus.OK);
	}

	@RequestMapping(value = "/liveDone", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> liveDone(@RequestBody JSONObject json){
		String planId = json.getString("id");
		logger.error("=======liveDone=======直播计划变更为结束状态==========="+json.toJSONString());
		LivePlan livePlan = livePlanService.getById(Integer.valueOf(planId));
		if (livePlan==null){
			return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C90001), HttpStatus.OK);
		}
		if (livePlan.getStatus()!=2){
			return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C90008), HttpStatus.OK);
		}
		redisUtil.del(RedisKeys.LIVE_ROOM_EXECUT_LIVE_PLAN+planId);
		redisUtil.del(RedisKey.REDIS_KEY_LIVEROOM_PLAN_MODEL);
		redisUtil.del(RedisKey.REDIS_KEY_LIVE_PLAN_DETAIL+planId);
		//删除计划列表重新缓存 从缓存获取直播计划的点赞总数更新到liveplan表中，下发消息给聊天室告诉app端直播已经结束
        int count = livePlanService.endLiving(planId);
		return new ResponseEntity<>(new ResponseResultModel<>(null), HttpStatus.OK);
	}

	@RequestMapping(value = "/refreshCache", method = RequestMethod.POST, consumes = "application/json")
    public ResponseEntity<?> refreshCache(@RequestBody JSONObject json){
	    String planId = json.getString("id");
	    redisUtil.del(RedisKey.REDIS_KEY_LIVEROOM_PLAN_MODEL);
	    redisUtil.del(RedisKey.REDIS_KEY_LIVE_PLAN_DETAIL+planId);
	    redisUtil.del(RedisKeys.LIVE_SALE_GOODS+planId);
        return new ResponseEntity<>(new ResponseResultModel<>(null), HttpStatus.OK);
    }

    @RequestMapping(value = "/refreshLivePlan", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> refreshLivePlan(@RequestBody JSONObject json){
		logger.error("======refreshLivePlan========刷新直播计划对象及首页直播计划缓存==========="+json.toJSONString());
		String planId = json.getString("id");
		redisUtil.del(RedisKey.REDIS_KEY_LIVE_PLAN_DETAIL+planId);
        redisUtil.del(RedisKey.REDIS_KEY_LIVEROOM_PLAN_MODEL);
        return new ResponseEntity<>(new ResponseResultModel<>(null), HttpStatus.OK);
	}

	@RequestMapping(value = "/addUser", method = RequestMethod.POST, consumes = "application/json")
    public ResponseEntity<?> addUser(@RequestBody JSONObject json){
	    String planId = json.getString("id");
 		logger.error("======addUser========管理页面往直播间动态加人==========="+json.toJSONString());
        redisUtil.del(RedisKey.REDIS_KEY_LIVE_PLAN_DETAIL+planId);
        String likeTotal = redisUtil.get(RedisKeys.LIVE_PLAN_TOTAL_LIKE_NUM+planId)==null?0+"":redisUtil.get(RedisKeys.LIVE_PLAN_TOTAL_LIKE_NUM+planId);
        LivePlan livePlan = livePlanService.getById(Integer.valueOf(planId));
        if (livePlan==null){
            return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C90001), HttpStatus.OK);
        }
        /*JSONObject json = new JSONObject();
        json.put("liveUserId",livePlan==null?0:livePlan.getLiveuserId());*/
//        String chatUser = queryRoomUsers(json);
        String joinUserNum = redisUtil.get(RedisKeys.LIVE_PLAN_USER_NUMBER+planId);
        int userNum = joinUserNum==null?0:Integer.valueOf(joinUserNum);/*JSONObject.parseObject(chatUser).getJSONObject("data").getIntValue("total");*/
		ChatRoomDateMessage chatRoomDateMessage = new ChatRoomDateMessage(userNum+livePlan.getAddUserNum(),likeTotal==null?0:Integer.valueOf(likeTotal));
        chatRoomService.mngSendMessage(Integer.valueOf(planId),chatRoomDateMessage);
        return new ResponseEntity<>(new ResponseResultModel<>(null), HttpStatus.OK);
    }

	@RequestMapping(value = "/getPushUrl", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getPushUrl(@RequestBody JSONObject json){
		String planId = json.getString("id");
		logger.error("======getPushUrl========获取推流地址==========="+json.toJSONString());
		LivePlan livePlan = livePlanService.getById(Integer.valueOf(planId));
		if (livePlan==null){
			return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C90001), HttpStatus.OK);
		}
		ChatRoomInfo[] chatroomCreateChatRoomInfo = { new ChatRoomInfo(planId, "") };
		try {
			CodeSuccessResult chatroomCreateResult = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).chatroom
					.create(chatroomCreateChatRoomInfo);
			// RongCloud.getInstance(IMConfig.appKey,
			// IMConfig.appSecret).chatroom.keepLive(uid);
		} catch (Exception e) {
			logger.error("聊天室初始化失败，请重试", e);
			//return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
		Long currentTime = (System.currentTimeMillis() / 1000) + CommonConstants.LIVE_KEY_VALID_TIME;
		String keyString = "/" + LiveConfig.appName + "/" + planId + "-" + currentTime + "-0-0-"
				+ LiveConfig.validKey;
		String md5Str = DigestUtils.md5Hex(keyString);
		String pushUrl = LiveConfig.pushUrl + LiveConfig.appName + "/" + planId + "?vhost=" + LiveConfig.vhost
				+ "&auth_key=" + currentTime + "-0-0-" + md5Str;
		JSONObject result = new JSONObject();
		result.put("pushUrl",pushUrl);
		return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
	}

	@RequestMapping(value = "sendChatRoomMessage",method = RequestMethod.POST,consumes = "application/json")
	public ResponseEntity<?> sendChatRoomMessage(@RequestBody JSONObject jsonObject){
		String planId = jsonObject.getString("id");
		String content = jsonObject.getString("content");
		JSONObject json = new JSONObject();
		json.put("toChatroomId",planId);
		json.put("text",content);
		chatRoomService.randomPublish(json);
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		long st = System.currentTimeMillis();
		for (int i = 0; i < 10000; i++) {
			System.out.println(RandomCharUtil.randomNickName((int)(Math.random()*3)));
		}
		System.out.println(System.currentTimeMillis()-st);
	}

	@RequestMapping(value = "shareLivePlan",method = RequestMethod.POST,consumes = "application/json")
	public ResponseEntity<?> shareLivePlan(@RequestBody JSONObject jsonObject,HttpServletRequest request){
		if (ParameterUtils.validParams(jsonObject.getIntValue("id"),request.getHeader("userId"))) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
		}
		LivePlan livePlan = livePlanService.getById(jsonObject.getIntValue("id"));
		if (livePlan==null){
			return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C90001), HttpStatus.OK);
		}
		if (livePlan.getStatus()!=2){
			return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C90008), HttpStatus.OK);
		}
		String uri = baseRestrictionsService.getBaseRestrictionsForCache("share_live_plan_link").getName();
		uri +="_id="+jsonObject.getIntValue("id");
		String h5_link = baseRestrictionsService.getBaseRestrictionsForCache("h5_link").getName();
		Map<String ,Object> map = new HashMap<>();
		StringBuffer shareBuff = new StringBuffer();
		shareBuff.append(h5_link).append(uri).append("&talentId="+request.getHeader("userId")).append("&share=1");
		map.put("shareUrl", LinkUtil.generateSinaShortUrl(shareBuff.toString()));
		map.put("title", livePlan.getShareTitle());
		map.put("imageUrl",livePlan.getShareImgUrl());
		map.put("name",livePlan.getShareContent());
		LiveShareRecord liveShareRecord = new LiveShareRecord();
		liveShareRecord.setGoodsId(0);
		liveShareRecord.setLivePlanId(jsonObject.getIntValue("id"));
		liveShareRecord.setUserId(Integer.valueOf(request.getHeader("userId")));
		liveShareRecord.setShareType(0);
		liveShareRecordService.add(liveShareRecord);
		return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
	}

	@RequestMapping(value = "/liveShareClickRecord", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> liveShareClickRecord(@RequestBody LiveShareClickRecord liveShareClickRecord){
		try {
			int count = liveShareClickRecordService.add(liveShareClickRecord);
			if (count>0){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			}else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			}
		}catch (Exception e){
			logger.error("liveShareClickRecord=====error===="+JSONObject.toJSONString(liveShareClickRecord));
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	@RequestMapping(value = "getH5Num",method = RequestMethod.POST,consumes = "application/json")
	public ResponseEntity<?> getH5Num(@RequestBody JSONObject json){
		Map<String ,Object> map = new HashMap<>();
		long count = redisUtil.zCount(RedisKey.REDIS_KEY_LIVE_H5_RECORD_SET+json.getIntValue("id"),System.currentTimeMillis()-(30*1000),System.currentTimeMillis()+1000);
		map.put("count",count);
		return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
	}

	@RequestMapping(value = "getShareRankingList",method = RequestMethod.POST,consumes = "application/json")
	public ResponseEntity<?> getShareRankingList(@RequestBody JSONObject json){
		int id = json.getIntValue("id");
		int userId = json.getIntValue("userId");
		List<ShareRankingListVo> list = liveShareClickRecordService.getShareRankingList(id,userId);
		Map<String ,Object> map = new HashMap<>();
		map.put("list",list);
		if (userId==0){
			map.put("ownCount",0);
		}else{
			int count = 0;
			int flag = 0;
			if (list!=null && list.isEmpty()){
				for (ShareRankingListVo s: list) {
					if (s.getOwnFlag()==1){
						count = s.getCount();
						flag=1;
					}
				}
			}
			if (flag==1){
				map.put("ownCount",count);
			}else{
				count = liveShareClickRecordService.getshareCountByUid(id,userId);
				map.put("ownCount",count);
			}
		}
		return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
	}

	@RequestMapping(value = "/sendRedPackage",method = RequestMethod.POST,consumes = "application/json")
	public ResponseEntity<?> sendRedPackage(@RequestBody JSONObject jsonObject){
		//调用红包模块功能传入生成具体的明细红包及主红包
		//往聊天室发送红包
		RedPackageMessage redPackageMessage = new RedPackageMessage(jsonObject.getIntValue("redPackageId"));
		chatRoomService.mngSendMessage(jsonObject.getIntValue("id"),redPackageMessage);
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}


	@RequestMapping(value = "/pushInfo",method = RequestMethod.POST,consumes = "application/json")
	public ResponseEntity<?> pushInfo(HttpServletRequest request){
		if (ParameterUtils.validParams(request.getHeader("userId"))) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
		}
	    // 创建直播计划及直播计划关联商品并返回直播推流地址
		return null;
	}

}
